// pages/userMsg/userMsg.js
const app = getApp();
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    avatarUrl: defaultAvatarUrl,
    nickName: '',
    adminArr: [],
    subAdminArr: [],
    showGetPhone: false,
    addRouter: '',
    isAgreed: false, // 是否同意复选框状态
  },

  getAdmin() {
    wx.request({
      url: `${app.globalData.baseUrl}/api/accounting/selManage`,
      method: "GET",
      header: {
        'token': wx.getStorageSync('token'),
        "Content-Type": "application/json"
      },
      success: (res) => {
        if (res.data.code == 0) {
          const arr = [];
          const subArr = [];
          res.data.data?.forEach(item => {
            if (item.status === '1') arr.push(item.tel);
            if (item.status === '0') subArr.push(item.tel);
          });
          this.setData({ adminArr: arr, subAdminArr: subArr });
        } else {
          wx.showToast({
            title: res.data.msg || '出错啦！',
            icon: 'error',
            duration: 2000
          })
        }
      }
    })
  },

  onChooseAvatar(e) {
    const { avatarUrl } = e.detail;
    const _that = this;
    wx.showToast({
      title: '正在上传...',
      icon: 'loading',
      mask: true,
      duration: 1000
    });
    wx.uploadFile({
      url: `${app.globalData.baseUrl}/common/upload`,
      filePath: avatarUrl,
      name: 'file',
      formData: {
        'user': 'test'
      },
      success: function (res) {
        const datas = JSON.parse(res.data);
        _that.setData({
          avatarUrl: datas.url,
        })
        wx.showToast({
          title: '图片上传成功',
          icon: 'loading',
          showCancel: false,
          duration: 1000
        })
      },
      fail: function (res) {
        wx.hideToast();
        wx.showModal({
          title: '错误提示',
          content: '上传图片失败',
          showCancel: false,
          success: function (res) { }
        })
      }
    });
  },

  nickBlur(e) {
    const { value } = e.detail
    this.setData({
      nickName: value,
    })
  },

  nickInput(e) {
    const { value } = e.detail
    this.setData({
      nickName: value,
    })
  },

  formSubmit(e) {
    if (this.data.nickName == '') {
      wx.showToast({
        title: '请输入用户名',
        icon: 'none'
      });
      return;
    }
    var reRule = /\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g;
    if (this.data.nickName.match(reRule)) {
      wx.showToast({
        title: '用户名不允许输入表情',
        icon: 'none'
      });
      return;
    }

    if (!this.data.isAgreed) {
      wx.showToast({
        title: '请先阅读并同意政策',
        icon: 'none'
      });
      return;
    }
    wx.setStorageSync('hasAgreedToPrivacyPolicy', true);
    const that = this;
    wx.login({
      success(res) {
        if (res.code) {
          wx.showLoading({
            title: '登陆中',
            icon: "loading"
          })
          wx.request({
            url: 'https://repair.zhaishu.store/api/login/getOpenids',
            method: "POST",
            data: {
              code: res.code,
              iv: wx.getStorageSync('iv'),
              encryptedData: wx.getStorageSync('encryptedData'),
            },
            header: {
              "Content-Type": "application/json"
            },
            success: (result) => {
              wx.hideLoading()
              if (result.data.code == 0) {
                wx.setStorageSync('openId', result.data.msg);
                wx.request({
                  url: 'https://repair.zhaishu.store/api/login/registers',
                  method: "POST",
                  data: {
                    openId: result.data.msg,
                    headPortrait: that.data.avatarUrl,
                    nickName: that.data.nickName,
                    tel: wx.getStorageSync('userPhone') || ''
                  },
                  header: {
                    "Content-Type": "application/json"
                  },
                  success: (res) => {
                    wx.hideLoading()
                    if (res.data.code == 0) {
                      wx.hideLoading();
                      wx.showToast({
                        title: res.data.msg || '报错啦！',
                        icon: 'success',//当icon：'none'时，没有图标 只有文字
                        duration: 2000
                      })
                      wx.setStorageSync('token', res.data.data.token);
                      wx.setStorageSync('userId', res.data.data.user.id);
                      wx.setStorageSync('nickName', that.data.nickName);
                      wx.setStorageSync('headPortrait', that.data.avatarUrl);
                      if (res.data.data.user.tel) {
                        wx.setStorageSync('userPhone', res.data.data.user.tel);
                      }
                      if (that.data.subAdminArr.indexOf(res.data.data.user.tel.toString()) > -1) {
                        wx.setStorageSync('subAdmin', 1);
                      } else {
                        wx.setStorageSync('subAdmin', 0);
                      };
                      if (res.data.data.user?.tel && that.data.adminArr.indexOf(res.data.data.user.tel?.toString()) > -1) {
                        wx.setStorageSync('admin', 1);
                      } else {
                        wx.setStorageSync('admin', 0);
                      };

                      wx.switchTab({
                        url: '/pages/index/index',
                      });
                      // } else {
                      //   that.setData({ showGetPhone: true });
                      // }
                    } else {
                      wx.showToast({
                        title: '系统错误',
                      })
                    }
                  }
                })
              } else {
                wx.showToast({
                  title: '系统错误',
                })
              }
            }
          })
        }
      }
    })
  },

  // 同意复选框点击事件
  onAgreeClick() {
    this.setData({
      isAgreed: !this.data.isAgreed
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.hideShareMenu();
    this.getAdmin();
    // if(!wx.getStorageSync('userPhone')) {
    //   this.setData({ showGetPhone: true });
    // }
  },

  closePhone() {
    this.setData({ showGetPhone: false });
  },

  linkPrivacyPolicy() {
    wx.navigateTo({
      url: '/pages/privacyPolicy/index',
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})